package cn.xiaoxiang.org.service.impl;

import cn.xiaoxiang.PethomeApp;
import cn.xiaoxiang.basic.service.impl.BaseServiceImpl;
import cn.xiaoxiang.basic.util.PageList;
import cn.xiaoxiang.org.domain.Department;
import cn.xiaoxiang.org.mapper.DepartmentMapper;
import cn.xiaoxiang.org.query.DepartmentQuery;
import cn.xiaoxiang.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;




    @Override
    public List<Department> tree() {
        List<Department> result = new ArrayList<>();
        // 查询出所有的数据
        List<Department> allDepartments = departmentMapper.findAll();
        // 将 全部的部门数据 转成map key  value

        Map<Long, Department> deptMap = new HashMap<>();
        allDepartments.forEach(dept->{
            deptMap.put(dept.getId(),dept);
        });
        // 在内存中组装数据
        for (Department dept : allDepartments) {
            if (null == dept.getParentId()){
                // 这就是一级数据
                result.add(dept);
            }else {
                // 这个是儿子 dept对象 它不是爹 那么它有几个爹
                Department parent = deptMap.get(dept.getParentId());
                parent.getChildren().add(dept);
            }
        }
        return result;
    }


}
